package com.caifu.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.caifu.bean.PrintUtil;
import com.caifu.bean.Result;
import com.caifu.bean.ResultUtil;
import com.caifu.pojo.ZcOrdering;
import com.caifu.service.UtilService;
import com.caifu.service.ZcOrderingService;
import com.caifu.util.AesMyUtil;
import com.caifu.util.Util;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.*;

/**
 * <p>
 * 订餐记录表 前端控制器
 * </p>
 *
 * @author szt
 * @since 2020-11-09
 */
@Controller
@RequestMapping("/ordering")
public class ZcOrderingController extends AbstractController{

    @Autowired
    private ZcOrderingService orderingService;

    @Autowired
    private UtilService utilService;

    @RequiresPermissions("dingdanguanli_read")
    @GetMapping("/index")
    public String index(ModelMap map) {
        String nextMonth = Util.dateCalculation_month(new Date(),1,"yyyyMM");
        map.put("nextMonth",nextMonth);
        return "foodDelivery/orderingRecords/index";
    }

    @PostMapping("/hasMonthOrder")
    @ResponseBody
    public Result hasMonthOrder(String orgId,String month) {
       try{
           int count = orderingService.count(new QueryWrapper<ZcOrdering>().eq("month",month).eq("org_id",orgId).ne("status","9"));
           if(count > 0){
               return new Result(200,"查询成功！","no");
           }else{
               return new Result(200,"查询成功！","yes");
           }
       }catch (Exception e){
           e.printStackTrace();
           return ResultUtil.error(-1,"查询失败！");
       }
    }

    @PostMapping("getData")
    @ResponseBody
    public Result getData(String type,int page,int pageSize,String name,String orgId,String state){
        try{
            String msg = "获取数据成功！";
            int start = (page - 1) * pageSize;
            List<String> orgList = new ArrayList<>();
            if(StringUtils.isNotBlank(orgId)) {
                List<Map<String,String>> orgs = utilService.getJurisdictionByParentNo(Integer.parseInt(orgId));
                if(orgs != null && orgs.size() > 0){
                    for(Map<String,String> m : orgs){
                        orgList.add(String.valueOf(m.get("org_id")));
                    }
                }
            }else{
                orgList = utilService.getJurisdiction(getUserNo());
            }
            String month = "";
            String symbol = "";
            if("1".equals(type)){
                month = Util.dateToString(null,"yyyyMM");
                symbol = "=";
            }else if("2".equals(type)){
                month = Util.dateCalculation_month(new Date(),1,"yyyyMM");
                symbol = "=";
            }else if("3".equals(type)){
                month = Util.dateCalculation_month(new Date(),-1,"yyyyMM");
                symbol = "<=";
            }else{
                month = "0";
                symbol = "=";
            }
            List<Map<String,String>> list = orderingService.getOrderList(start,pageSize,name,orgList,state,month,symbol);
            int count = orderingService.getOrderListCount(name,orgList,state,month,symbol);
            if(count <= 0){
                msg = "暂无数据！";
            }
            return new Result(0,msg,count,list);
        }catch (Exception e){
            e.printStackTrace();
            return ResultUtil.error(-1,"获取数据失败！");
        }
    }

    @PostMapping("batchDeliver")
    @ResponseBody
    public Result batchDeliver(String type,String name,String orgId){
        try{
            String msg = "批量交付配餐成功！";
            List<String> orgList = new ArrayList<>();
            if(StringUtils.isNotBlank(orgId)) {
                List<Map<String,String>> orgs = utilService.getJurisdictionByParentNo(Integer.parseInt(orgId));
                if(orgs != null && orgs.size() > 0){
                    for(Map<String,String> m : orgs){
                        orgList.add(String.valueOf(m.get("org_id")));
                    }
                }
            }else{
                orgList = utilService.getJurisdiction(getUserNo());
            }
            String month = "";
            if("2".equals(type)){
                month = Util.dateCalculation_month(new Date(),1,"yyyyMM");
            }
            String flag = orderingService.batchDeliver(name,orgList,month,getUserNo());
            if("0".equals(flag)){
                msg = "批量交付配餐失败！";
            }else if("2".equals(flag)){
                msg = "当前暂无需要交付的配餐（注：上报片区后才能交付配餐）！";
            }
            return new Result(200,msg,null);
        }catch (Exception e){
            e.printStackTrace();
            return ResultUtil.error(-1,"批量交付配餐失败！");
        }
    }

    @PostMapping("getPlatformData")
    @ResponseBody
    public Result getPlatformData(int page,int pageSize,String orgId,String dateType,String startDate,String endDate,String type,String orderStatus){
        try{
            String msg = "获取数据成功！";
            int start = (page - 1) * pageSize;
            List<String> orgList = new ArrayList<>();
            if(StringUtils.isNotBlank(orgId)) {
                List<Map<String,String>> orgs = utilService.getJurisdictionByParentNo(Integer.parseInt(orgId));
                if(orgs != null && orgs.size() > 0){
                    for(Map<String,String> m : orgs){
                        orgList.add(String.valueOf(m.get("org_id")));
                    }
                }
            }else{
                orgList = utilService.getJurisdiction(getUserNo());
            }
            if(orgList.size() > 0) {
                if (StringUtils.isNotBlank(startDate)) {
                    startDate = startDate.replace("-", "");
                }
                if (StringUtils.isNotBlank(endDate)) {
                    endDate = endDate.replace("-", "");
                }
                if (dateType.equals("1")) {
                    startDate = Util.dateToString(null, "yyyyMMdd");
                    endDate = startDate;
                } else if (dateType.equals("2")) {
                    startDate = Util.dateToString(null, "yyyyMMdd");
                    endDate = Util.dateCalculation(startDate, "yyyyMMdd", 1);
                } else if (dateType.equals("3")) {
                    startDate = Util.dateToString(null, "yyyyMMdd");
                    endDate = Util.dateCalculation(startDate, "yyyyMMdd", 2);
                }else if (dateType.equals("5")) {
                    String now = Util.dateToString(null,"yyyyMM");
                    startDate = now+"01";
                    Date month = Util.stringToDate(startDate,"yyyyMMdd");
                    Calendar cal = Calendar.getInstance();
                    cal.setTime(month);
                    int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
                    endDate = now + lastDay;
                }else if (dateType.equals("6")) {
                    String now = Util.dateToString(null,"yyyyMM");
                    now = Util.dateCalculation_month(Util.stringToDate(now+"01","yyyyMMdd"),1,"yyyyMM");
                    startDate = now+"01";
                    Date month = Util.stringToDate(startDate,"yyyyMMdd");
                    Calendar cal = Calendar.getInstance();
                    cal.setTime(month);
                    int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
                    endDate = now + lastDay;
                }
                List<Map<String, String>> list = orderingService.getPlatformData(start, pageSize, startDate, endDate, type, orderStatus, orgList);
                if(list != null && list.size() > 0){
                    for(Map<String,String> map : list){
                        map.put("food_date",Util.stringDateToStringDate(map.get("month")+map.get("day"),"yyyyMMdd","yyyy-MM-dd"));
                        if(map.get("type").equals("1")){
                            map.put("type_str","午餐");
                        }else if(map.get("type").equals("2")){
                            map.put("type_str","晚餐");
                        }else {
                            map.put("type_str","未知");
                        }
                        if(map.get("distribution_status").equals("1")){
                            map.put("distribution_status","待配送");
                        }else if(map.get("distribution_status").equals("2")){
                            map.put("distribution_status","已配送");
                        }else {
                            map.put("distribution_status","未知");
                        }
                    }
                }
                int count = orderingService.getPlatformDataCount(startDate, endDate, type, orderStatus, orgList);
                if(count <= 0){msg = "暂无数据！";}
                return new Result(0, msg, count, list);
            }else{
                return ResultUtil.error(-1,"暂无数据权限！");
            }
        }catch (Exception e){
            e.printStackTrace();
            return ResultUtil.error(-1,"获取数据失败！");
        }
    }

    @PostMapping("getPlatformDetails")
    @ResponseBody
    public Result getPlatformDetails(String data){
        try{
            List<Map<String, Object>> result = new ArrayList<>();
            if(StringUtils.isNotBlank(data)) {
                JSONArray arr = JSONArray.fromObject(data);
                if(arr != null && arr.size() > 0) {
                    for(int i = 0 ; i < arr.size() ; i ++) {
                        Map<String, Object> map = new HashMap<>();
                        JSONObject object = arr.getJSONObject(i);
                        String id = object.getString("id");
                        String month = object.getString("month");
                        String day = object.getString("day");
                        String type = object.getString("type");
                        Map<String, String> info = orderingService.getDetailsInfo(id, month, day, type);
                        Map<String, String> fixedPoint = orderingService.getDetailsFixedPoint(id, month, day, type);
                        List<Map<String, String>> toDoor = orderingService.getDetailsToDoor(id, month, day, type);
                        Object obj = null;
                        if (info != null && info.size() > 0) {
                            obj = info.get("org_name");
                            String orgName = "";
                            String typeStr = "";
                            if (isNotNull(obj)) {
                                orgName = String.valueOf(obj);
                            }
                            if (info.get("food_type").equals("1")) {
                                typeStr = "午餐";
                            } else if (info.get("food_type").equals("2")) {
                                typeStr = "晚餐";
                            }
                            info.put("title", orgName + "-" + typeStr + "-" + String.valueOf(info.get("count")) + "份");
                            info.put("date", String.valueOf(info.get("month")).substring(0, 4) + "-" + String.valueOf(info.get("month")).substring(4, 6) + "-" + String.valueOf(info.get("day")));
                        }
                        if (toDoor != null && toDoor.size() > 0) {
                            for (Map<String, String> m : toDoor) {
                                obj = m.get("zd_user_name");
                                if (isNotNull(obj)) {
                                    m.put("user_name", String.valueOf(obj));
                                } else {
                                    obj = m.get("fd_user_name");
                                    if (isNotNull(obj)) {
                                        m.put("user_name", String.valueOf(obj));
                                    } else {
                                        m.put("user_name", "");
                                    }
                                }
                                obj = m.get("mobile");
                                if (isNotNull(obj)) {
                                    m.put("mobile", AesMyUtil.Decrypt(String.valueOf(obj)));
                                } else {
                                    m.put("mobile", "");
                                }
                            }
                        }
                        map.put("info", info);
                        map.put("fixedPoint", fixedPoint);
                        map.put("toDoor", toDoor);
                        result.add(map);
                    }
                    return new Result(200, "获取数据成功！", result);
                }else{
                    return ResultUtil.error(-1,"获取数据失败！");
                }
            }else{
                return ResultUtil.error(-1,"获取数据失败！");
            }
        }catch (Exception e){
            e.printStackTrace();
            return ResultUtil.error(-1,"获取数据失败！");
        }
    }

    @PostMapping("printOrder")
    @ResponseBody
    public Result printOrder(String data){
        try{
            List<Map<String, Object>> result = new ArrayList<>();
            if(StringUtils.isNotBlank(data)) {
                JSONArray arr = JSONArray.fromObject(data);
                if(arr != null && arr.size() > 0) {
                    for(int i = 0 ; i < arr.size() ; i ++) {
                        Map<String, Object> map = new HashMap<>();
                        JSONObject object = arr.getJSONObject(i);
                        String id = object.getString("id");
                        String month = object.getString("month");
                        String day = object.getString("day");
                        String type = object.getString("type");
                        Map<String, String> info = orderingService.getDetailsInfo(id, month, day, type);
                        Map<String, String> fixedPoint = orderingService.getDetailsFixedPoint(id, month, day, type);
                        List<Map<String, String>> toDoor = orderingService.getDetailsToDoor(id, month, day, type);
                        Object obj = null;
                        if (info != null && info.size() > 0) {
                            obj = info.get("org_name");
                            String orgName = "";
                            String typeStr = "";
                            if (isNotNull(obj)) {
                                orgName = String.valueOf(obj);
                            }
                            if (info.get("food_type").equals("1")) {
                                typeStr = "午餐";
                            } else if (info.get("food_type").equals("2")) {
                                typeStr = "晚餐";
                            }
                            info.put("title", orgName + "-" + typeStr + "-" + String.valueOf(info.get("count")) + "份");
                            info.put("date", String.valueOf(info.get("month")).substring(0, 4) + "-" + String.valueOf(info.get("month")).substring(4, 6) + "-" + String.valueOf(info.get("day")));
                        }
                        if (toDoor != null && toDoor.size() > 0) {
                            for (Map<String, String> m : toDoor) {
                                obj = m.get("zd_user_name");
                                if (isNotNull(obj)) {
                                    m.put("user_name", String.valueOf(obj));
                                } else {
                                    obj = m.get("fd_user_name");
                                    if (isNotNull(obj)) {
                                        m.put("user_name", String.valueOf(obj));
                                    } else {
                                        m.put("user_name", "");
                                    }
                                }
                                obj = m.get("mobile");
                                if (isNotNull(obj)) {
                                    m.put("mobile", AesMyUtil.Decrypt(String.valueOf(obj)));
                                } else {
                                    m.put("mobile", "");
                                }
                            }
                        }
                        map.put("info", info);
                        map.put("fixedPoint", fixedPoint);
                        map.put("toDoor", toDoor);
                        result.add(map);
                    }
                    PrintUtil pu = new PrintUtil();
                    pu.init(result);
                    return new Result(200, "打印操作完成！", result);
                }else{
                    return ResultUtil.error(-1,"打印失败！");
                }
            }else{
                return ResultUtil.error(-1,"无打印数据！");
            }
        }catch (Exception e){
            e.printStackTrace();
            return ResultUtil.error(-1,"打印失败！");
        }
    }

    @PostMapping("testPrint")
    @ResponseBody
    public Result testPrint(HttpServletRequest request){
        try{
            List<Map<String, Object>> result = new ArrayList<>();

            Map<String,Object> map1 = new HashMap<>();
            Map<String,String> info1 = new HashMap<>();
            Map<String,String> fixedPoint1 = new HashMap<>();
            List<Map<String,String>> toDoor1 = new ArrayList<>();

            info1.put("title","安亭片-中餐-33份");
            info1.put("date","2020-12-22");
            fixedPoint1.put("count","30");
            fixedPoint1.put("address","上海市嘉定区安亭片XXX");
            fixedPoint1.put("address","上海市嘉定区安亭片XXX");
            for(int i = 5;i>0;i--){
                Map<String,String> m = new HashMap<>();
                m.put("user_name","郭靖");
                m.put("mobile","1518452412"+i);
                m.put("address","上海市嘉定区安亭片桃花岛"+i);
                toDoor1.add(m);
            }

            map1.put("info",info1);
            map1.put("fixedPoint",fixedPoint1);
            map1.put("toDoor",toDoor1);

            Map<String,Object> map2 = new HashMap<>();
            Map<String,String> info2 = new HashMap<>();
            Map<String,String> fixedPoint2 = new HashMap<>();
            List<Map<String,String>> toDoor2 = new ArrayList<>();

            info2.put("title","安亭片-中餐-30份");
            info2.put("date","2020-12-22");
            fixedPoint2.put("count","27");
            fixedPoint2.put("address","上海市嘉定区安亭片XXX");
            fixedPoint2.put("address","上海市嘉定区安亭片XXX");
           /* for(int i = 3;i>0;i--){
                Map<String,String> m = new HashMap<>();
                m.put("user_name","郭靖");
                m.put("mobile","1518452412"+i);
                m.put("address","上海市嘉定区安亭片桃花岛"+i);
                toDoor2.add(m);
            }*/

            map2.put("info",info2);
            map2.put("fixedPoint",fixedPoint2);
            map2.put("toDoor",toDoor2);

            result.add(map1);
            result.add(map2);

            /*PrintUtil pu = new PrintUtil();
            pu.init(result);*/
            return new Result(200, "打印操作完成！", result);
        }catch (Exception e){
            e.printStackTrace();
            return ResultUtil.error(-1,"打印失败！");
        }
    }


    @PostMapping("reporting")
    @ResponseBody
    public Result reporting(String id){
        try{
            orderingService.update(null,new UpdateWrapper<ZcOrdering>().set("status","2").set("update_by",getUserNo()).set("update_time",new Date()).eq("id",id));
            return new Result(200, "上报片区成功！", null);
        }catch (Exception e){
            e.printStackTrace();
            return ResultUtil.error(-1,"上报片区失败！");
        }
    }


    @PostMapping("deliver")
    @ResponseBody
    public Result deliver(String id){
        try{
            orderingService.update(null,new UpdateWrapper<ZcOrdering>().set("status","3").set("order_time",new Date()).set("order_by",getUserNo()).eq("id",id));
            return new Result(200, "交付配餐成功！", null);
        }catch (Exception e){
            e.printStackTrace();
            return ResultUtil.error(-1,"交付配餐失败！");
        }
    }

    @PostMapping("delete")
    @ResponseBody
    public Result delete(String id){
        try{
            orderingService.deleteOrder(id);
            return new Result(200, "删除订单成功！", null);
        }catch (Exception e){
            e.printStackTrace();
            return ResultUtil.error(-1,"删除订单失败！");
        }
    }

    @PostMapping("getUserOrg")
    @ResponseBody
    public Result getUserOrg(){
        try{
            return new Result(200, "获取村/社区成功！", orderingService.getUserOrg(getUserNo()));
        }catch (Exception e){
            e.printStackTrace();
            return ResultUtil.error(-1,"获取村/社区失败！");
        }
    }

    private boolean isNotNull(Object obj){
        if(obj != null && StringUtils.isNotBlank(String.valueOf(obj)) && !"null".equals(String.valueOf(obj))) {
            return true;
        }else{
            return false;
        }
    }


    /**
     * 获取当前网络ip
     * @param request
     * @return
     */
    private String getIpAddr(HttpServletRequest request){
        String ipAddress = request.getHeader("x-forwarded-for");
        if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            System.out.println("remoteAddr:"+ipAddress);
            if(ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")){
                //根据网卡取本机配置的IP
                InetAddress inet=null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                ipAddress= inet.getHostAddress();
            }
        }
        //对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if(ipAddress!=null && ipAddress.length()>15){ //"***.***.***.***".length() = 15
            if(ipAddress.indexOf(",")>0){
                ipAddress = ipAddress.substring(0,ipAddress.indexOf(","));
            }
        }
        return ipAddress;
    }
}
